const { graphql, buildSchema } = require("graphql");
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const cors = require("cors");

const app = express();
app.use(cors());

// 1. 使用GraphQL schema语法构建一个 schema
const schema = buildSchema(`
  type Score {
    name: String
    score: Float
  }

  type User {
    name: String
    age: Int
    hobbies: [String!]!
    score: [Score]
  }

  type Article {
    title: String
    body: String
    author: User
  }

  # Query 严格来说是一种对象类型
  # Query 是所有查询的入口点
  # Query 必须有，并且只能有一个
  type Query {
    foo: String!
    count: Int
    salary: Float
    isGood: Boolean
    userId: ID
    user: User
    article: Article
  }
`);

// 2. 定义 resolver 函数，用于处理 GraphQL 请求
const rootValue = {
  foo() {
    return "bar";
  },
  count() {
    return 123;
  },
  salary() {
    return 123.45;
  },
  isGood() {
    return true;
  },
  userId() {
    return "1212";
  },
  user() {
    return {
      name: "Alice",
      age: 25,
      hobbies: ["reading", "swimming"],
      score: [
        { name: "Math", score: 90 },
        { name: "English", score: 85 },
      ],
    };
  },
  article() {
    return {
      title: "GraphQL 入门教程",
      body: "GraphQL 是一个用于 API 的查询语言",
      author: { name: "Bob", age: 30 },
    };
  },
};

// 3. 创建 Express 应用
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    rootValue,
    graphiql: true, // 开启浏览器 GraphQL IDE 调试工具
  })
);

app.listen(4000, () => {
  console.log("Server running at http://localhost:4000/graphql");
});

// 3. 查询
/* graphql(schema, "{ foo }", rootValue).then((result) => {
  console.log(result);
}); */
